﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using ImageResizer.Configuration;
using ImageResizer.Util;

namespace zkdao.WebImage {
    public class RouteConfig {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Photo", action = "Index", id = UrlParameter.Optional }
            );

            Config.Current.Pipeline.Rewrite += new UrlRewritingEventHandler(Pipeline_Rewrite);
            Config.Current.Pipeline.AuthorizeImage += new UrlAuthorizationEventHandler(Pipeline_AuthorizeImage);
        }

        static void Pipeline_AuthorizeImage(IHttpModule sender, HttpContext context, IUrlAuthorizationEventArgs e) {
            if (e.VirtualPath.StartsWith(PathUtils.ResolveAppRelative(PhotoStorePath), StringComparison.OrdinalIgnoreCase))
                e.AllowAccess = true;
        }

        static void Pipeline_Rewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e) {
            if (e.VirtualPath.StartsWith(PhotoVirtualPath, StringComparison.OrdinalIgnoreCase))
                e.VirtualPath = PathUtils.ResolveAppRelative(PhotoStorePath) + e.VirtualPath.Substring(PhotoVirtualPath.Length);
        }

        public static string PhotoVirtualPath {
            get {
                return ConfigurationManager.AppSettings["PhotoVirtualPath"];
            }
        }
        public static string PhotoStorePath {
            get {
                return ConfigurationManager.AppSettings["PhotoStorePath"];
            }
        }
    }
}